import datetime
import random
from pymongo import MongoClient
from apscheduler.schedulers.background import BackgroundScheduler
import requests
import json
from .models import storage,note_info,product,User,Demand, DemandDetail,shelf
from .models import warehouse as Warehouse
from django.db.models.aggregates import Sum


sched = BackgroundScheduler()

vechile_data = [[116.404 + random.random() * 0.5 - 0.25,
                 39.915 + random.random() * 0.5 - 0.25,
                 ("000" + str(i))[-3:],
                 str(i) + "司机",
                 "任务x",
                 "正常" if random.random() > 0.5 else "异常"]
                + [datetime.datetime.now().strftime("%Y-%m-%D %H:%M:%S")]
                for i in range(20)]


@sched.scheduled_job('interval', seconds=5)
def refresh_data():
    global vechile_data
    vechile_data = [[i[0] + random.random() * 0.005 - 0.0025,
                     i[1] + random.random() * 0.005 - 0.0025]
                    + i[2:-2] +
                    ["正常" if random.random() > 0.5 else "异常"]
                    + [datetime.datetime.now().strftime("%Y-%m-%D %H:%M:%S")]
                    for i in vechile_data]


# 取消该注释当系统启动后会一直往里写数据且要求能连接mongoDB
# @sched.scheduled_job('interval',seconds=5, args=["http://localhost:8000/vehicle_get"])
def save_data(data_url):
    web_page = requests.get(data_url)
    web_page.encoding = web_page.apparent_encoding
    content = eval(web_page.content.decode('unicode-escape'))['data']
    try:
        client = MongoClient('39.107.112.113', 27017, username="root", password="zhangtianze1997")
        db = client['milk_logistics']
        table = db.trucks
        for i in content:
            table.insert({'longitude': i[0], 'latitude': i[1], 'truck_id': i[2], 'driver': i[3],
                          'task': i[4], 'status': i[5], 'time': i[6]})
    except:
        print("cannot connect mongoDB")


# 每天定时检查是否过期
@sched.scheduled_job('cron', hour=0)
def check_expired():
    from .views import create_notification
    for i in storage.objects.filter(expired=False).all():
        if datetime.datetime.today() - datetime.timedelta(days=i.p_ID.p_expiration) > datetime.fromordinal(i.product_date.toordinal()):
            i.expired = True
            i.save()
            create_notification(str(i.shelf.s_id) + "的" + str(i.p_name) + "已过期,请及时处理",
                                note_type=1,
                                receiver_id=i.warehouse.user_set.first().id,
                                url="expired")


# 每天定时检查库存商品，生成需求单
@sched.scheduled_job('cron', hour=0)
def add_demand():
    warehouse_list = Warehouse.objects.all()
    # 未
    for warehouse1 in warehouse_list:
        total_storage = storage.objects.filter(warehouse_id=warehouse1.warehouse_id, expired=False).values("p_ID_id").annotate(sum=Sum("s_number"))
        goods = product.objects.all()
        t = datetime.datetime.now()
        demand_id = t.strftime('%Y%m%d%H') + str(warehouse1.warehouse_id)
        # 这里我写的是需求表id直接等于时间，可以改成别的
        Demand.objects.create(number=demand_id, datetime=t, isSolved="False", warehouse=warehouse1)
        demand1=Demand.objects.filter(number=demand_id).first()#得到刚建好的demand表
        # 接下来建需求详细表
        sgoodID = []
        # 来存储已经列好的商品id
        # 建立有库存的商品需求详细表——默认不补货
        # 采购量quantity为0，库存remain为实际库存
        for item in total_storage:
            p=product.objects.filter(p_ID=item["p_ID_id"]).first()
            DemandDetail.objects.create(demand=demand1, product=p, quantity=0, remain=item["sum"])
            sgoodID.append(item["p_ID_id"])
        for g in goods:
            if g.p_ID not in sgoodID:#还没有建需求详细表的商品
                sgoodID.append(g.p_ID)
                DemandDetail.objects.create(demand=demand1, product=g, quantity=5, remain=0)


sched.start()
